#ifndef __TGA_H__
#define __TGA_H__

#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>

//////////////////////////////////////////////////////////////////////////
// save to tga format - used for debugging purpose                      //
//////////////////////////////////////////////////////////////////////////


// saves an array of pixels as a TGA image
// based on source code from http://www.lighthouse3d.com/opengl/terrain/index.php3?tgasource

bool tgaSave(const TCHAR *filename, short int width, short int height, unsigned char pixelDepth, unsigned char* imageData)
{
	unsigned char cGarbage = 0, type, mode;
	short int iGarbage = 0;
	int i, j;
	FILE *file;
	unsigned char* row;
	unsigned char* imageDataRowPtr;
	bool result = true;

	// open file and check for errors
	file = _tfopen(filename, _T("wb"));
	if (file == NULL)
	{
		return false;
	}

	// compute image type: 2 for RGB(A), 3 for greyscale
	mode = pixelDepth / 8;
	if ((pixelDepth == 24) || (pixelDepth == 32))
		type = 2;
	else if(pixelDepth == 8)
		type = 3;
	else
		return 0;

	// write the header
	fwrite(&cGarbage, sizeof(unsigned char), 1, file);
	fwrite(&cGarbage, sizeof(unsigned char), 1, file);

	fwrite(&type, sizeof(unsigned char), 1, file);

	fwrite(&iGarbage, sizeof(short int), 1, file);
	fwrite(&iGarbage, sizeof(short int), 1, file);
	fwrite(&cGarbage, sizeof(unsigned char), 1, file);
	fwrite(&iGarbage, sizeof(short int), 1, file);
	fwrite(&iGarbage, sizeof(short int), 1, file);

	fwrite(&width, sizeof(short int), 1, file);
	fwrite(&height, sizeof(short int), 1, file);
	fwrite(&pixelDepth, sizeof(unsigned char), 1, file);

	fwrite(&cGarbage, sizeof(unsigned char), 1, file);

	// convert the image data from RGB(a) to BGR(A)

	if (mode >=3)
	{
		//RGB
		row = (unsigned char*)malloc(width * mode);
		if(row==NULL)
		{
			fclose(file);
			return false;
		}

		for (i=height - 1; i >= 0; i--)
		{
			imageDataRowPtr = imageData + width * i * mode;
			
			for(j = 0; j < width * mode; j+=mode)
			{
				//RGB -> BGR
				row[j + 2] = *imageDataRowPtr++;
				row[j + 1] = *imageDataRowPtr++;
				row[j + 0] = *imageDataRowPtr++;
				if(mode == 4)
				{
					row[j + 3] = *imageDataRowPtr++;
				}
			}
			fwrite(row, sizeof(unsigned char), width * mode, file);
		}
		free(row);
	}
	else if (mode == 1)
	{
		//greyscale
		// save the image data
		for (i=height - 1; i >= 0; i--)
		{
			imageDataRowPtr = imageData + width * i;
			
			fwrite(imageDataRowPtr, sizeof(unsigned char), width, file);
		}
	}
	else
	{
		result = false;
	}

	fclose(file);

	return result;
}

#endif//__TGA_H__
